#coding=utf-8
import os,re,logging,datetime,time,cgi,urllib
import wsgiref.handlers

from google.appengine.ext import db, webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.api.labs import taskqueue

from models import Ad

application = os.environ['APPLICATION_ID']
SERVER = '%s.appspotmail.com'%application
sender = "taobao@%s"%SERVER
re_email = re.compile(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)",re.IGNORECASE)

def get_mails():
  return urllib.urlopen('http://email-portal.appspot.com/get').read().split('<br/>')[:-1]

def get_ad():
  return Ad.all().order('-created_at').fetch(1)[0]

class Now(webapp.RequestHandler):
  def get(self):
    import datetime
    n = datetime.datetime.now()
    self.response.out.write(n)
    
class AdReceiver(webapp.RequestHandler):
  def post(self):
    a = Ad(campaign = self.request.get('campaign'),
            subject = self.request.get('subject'),
            plain_content = self.request.get('plain'),
            html_content = self.request.get('html'),
            )
    a.put()       
    self.response.out.write(a.to_html('xiaojay@gmail.com'))     
      
class MailSender(webapp.RequestHandler):
  def get(self):
    addr = self.request.get('email')
    
    ad = get_ad()
    ad.send_to(sender, addr)
    self.response.out.write(addr)

class MailSender2(webapp.RequestHandler):
  def get(self):
    emails = get_mails()
    ad = get_ad()
    for email in emails:
      ad.send_to(sender, email)
      self.response.out.write(email)
      
class Fire(webapp.RequestHandler):pass
  
class MailHandler(InboundMailHandler):
  def receive(self, message):
    _subject = message.subject
    _sender = message.sender
    bodies = message.bodies(content_type='text/plain')
    allBodies = "";
    for body in bodies:
        allBodies = allBodies + "\n---------------------------\n" + body[1].decode()  
    
    info = '发送者:%s\n标题:%s\n正文:%s\n'%(_sender, _subject, allBodies)
    logging.info(info)
        
    addrs = []
    emails = re_email.findall(allBodies)
    logging.info('*'.join(emails))
    for e in emails:
      if not e:continue
      e2 = e.strip()
      if e2.split('@')[-1] in [SERVER, 'google.com']:
          continue
      addrs.append(e2)
    addrs = list(set(addrs))
    logging.info('~'.join(addrs))
    for addr in addrs:
      post_rejected(addr, _subject, allBodies)
      
def post_rejected(email, subject, content):
  import urllib
  import urllib2

  url = 'http://email-portal.appspot.com/reject'
  values = {'email': email,
            'sub': subject,
            'content': content
            }
  
  data = urllib.urlencode(values)
  req = urllib2.Request(url, data)
  response = urllib2.urlopen(req)
  the_page = response.read()
  return the_page
         
application = webapp.WSGIApplication([
  ('/send_mail', MailSender),
  ('/send_mail2', MailSender2),
  ('/post_ad', AdReceiver),
  ('/now', Now),
  MailHandler.mapping(),
], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
